package edu.ucla.rendezvous.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class PacketParserUtil {

	public static String getString(byte[] buf) throws UnsupportedEncodingException {
		return new String(buf,"US-ASCII");
	}
	
	public static byte[] getBytes(String str) throws UnsupportedEncodingException {
		return str.getBytes("US-ASCII");
	}
	
	public static byte[] createPacket(String type, String data) {
		byte[] output = null;
		ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
		if(type.equals("HELLO")) {
			outputBuffer.write(0);
		} else if (type.equals("HELLO-REPLY")) {
			outputBuffer.write(1);
		} else if (type.equals("REFRESH")) {
			outputBuffer.write(2);
		} else if (type.equals("REFRESH-REPLY")) {
			outputBuffer.write(3);
		} else if (type.equals("PATH-REQUEST")) {
			outputBuffer.write(4);
		} else if (type.equals("PATH-REPLY")) {
			outputBuffer.write(5);
		} else if (type.equals("REQUEST-CHILDREN")) {
			outputBuffer.write(6);
		} else if (type.equals("REPLY-CHILDREN")) {
			outputBuffer.write(7);
		} else if (type.equals("JOIN-REQUEST")) {
			outputBuffer.write(8);
		} else if (type.equals("JOIN-REPLY")) {
			outputBuffer.write(9);
		} else if (type.equals("NOTIFY-LEAVE")) {
			outputBuffer.write(10);
		} else if (type.equals("DATA")) {
			outputBuffer.write(11);
		} else {
			outputBuffer.write(-1);
		}
		
		try {	// If we have a payload, append it. Then write the bytes out and close the stream.
			if(data != null) {
				outputBuffer.write(getBytes(data));
			}
			output = outputBuffer.toByteArray();
			outputBuffer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return output;
	}
	
	public static String getPacketType(byte[] pkt) {
		if(pkt[0] == 0) {
			return "HELLO";
		} else if(pkt[0] == 1) {
			return "HELLO-REPLY";
		} else if(pkt[0] == 2) {
			return "REFRESH";
		} else if(pkt[0] == 3) {
			return "REFRESH-REPLY";
		} else if(pkt[0] == 4) {
			return "PATH-REQUEST";
		} else if(pkt[0] == 5) {
			return "PATH-REPLY";
		} else if(pkt[0] == 6) {
			return"REQUEST-CHILDREN";
		} else if(pkt[0] == 7) {
			return"REPLY-CHILDREN";
		} else if(pkt[0] == 8) {
			return"JOIN-REQUEST";
		} else if(pkt[0] == 9) {
			return "JOIN-REPLY";
		} else if(pkt[0] == 10) {
			return "NOTIFY-LEAVE";
		} else if(pkt[0] == 11) {
			return "DATA";
		}
		return null;
	}
	
	public static String getPacketPayload(byte[] pkt) {
		String payload = null;
		try {
			payload = getString(pkt);
			payload = payload.substring(1);		// Chop off the first bit because it contains the packet type.
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return payload;
	}
	
}
